This stock market performance analysis will begin with importing real time stock price data for Apple, Microsoft, Netflix, and Google, for the last three months
import pandas as pd
import yfinance as yf
from datetime import datetime
start_date = datetime.now() - pd.DateOffset (months=3)
end_date = datetime.now()
tickers = ['AAPL', 'MSFT', 'NFLX', 'GOOG']
df_list = []
for ticker in tickers:
data = yf.download(ticker, start=start_date, end=end_date)
df_list.append(data)
df=pd.concat(df_list, keys=tickers, names=['Ticker', 'Date'])
print(df.head())
[*********************100%***********************] 1 of 1 completed
[*********************100%***********************] 1 of 1 completed
[*********************100%***********************] 1 of 1 completed
[*********************100%***********************] 1 of 1 completed
Open High Low Close Adj Close \
Ticker Date
AAPL 2023-02-13 150.949997 154.259995 150.919998 153.850006 153.637497
2023-02-14 152.119995 153.770004 150.860001 153.199997 152.988388
2023-02-15 153.110001 155.500000 152.880005 155.330002 155.115448
2023-02-16 153.509995 156.330002 153.350006 153.710007 153.497696
2023-02-17 152.350006 153.000000 150.850006 152.550003 152.339294
Volume
Ticker Date
AAPL 2023-02-13 62199000
2023-02-14 61707600
2023-02-15 65573800
2023-02-16 68167900
2023-02-17 59144100
The date column in the dataframe is the index column, hence, it'll be reset before moving forward.
df=df.reset_index()
print(df.head())
Ticker Date Open High Low Close \
0 AAPL 2023-02-13 150.949997 154.259995 150.919998 153.850006
1 AAPL 2023-02-14 152.119995 153.770004 150.860001 153.199997
2 AAPL 2023-02-15 153.110001 155.500000 152.880005 155.330002
3 AAPL 2023-02-16 153.509995 156.330002 153.350006 153.710007
4 AAPL 2023-02-17 152.350006 153.000000 150.850006 152.550003
Adj Close Volume
0 153.637497 62199000
1 152.988388 61707600
2 155.115448 65573800
3 153.497696 68167900
4 152.339294 59144100
Looking at the performance in the stock market of all the companies
import plotly.express as px
fig = px.line(df, x='Date',
y='Close',
color='Ticker',
title="Stock Market Performance for the Last 3 Months")
fig.show()
Using a faceted area chart, it'll be easy to compare the performance of different companies and identify similarities or differences in their stock price movement as shown below:
fig = px.area(df,x='Date',y='Close', color = 'Ticker',
facet_col = 'Ticker',
labels={'Date':'Date', 'Close':'Closing Price', 'Ticker':'Company'},
title='Stock Prices for Apple, Microsoft, Netflix, and Google')
fig.show()
To identify trends and patterns in each company's stock price movements over a period of time, we shall analyze moving averages.
## calculating the moving averages
df['MA10'] = df.groupby('Ticker')['Close'].rolling(window=10).mean().reset_index(0, drop=True)
df['MA20'] = df.groupby('Ticker')['Close'].rolling(window=20).mean().reset_index(0, drop=True)
for ticker, group in df.groupby('Ticker'):
print(f'Moving Averages for {ticker}')
print(group[['MA10', 'MA20']])
Moving Averages for AAPL
MA10 MA20
0 NaN NaN
1 NaN NaN
2 NaN NaN
3 NaN NaN
4 NaN NaN
.. ... ...
58 168.405998 166.6030
59 169.205998 167.1515
60 170.185999 167.8245
61 170.719998 168.2340
62 171.009000 168.6020
[63 rows x 2 columns]
Moving Averages for GOOG
MA10 MA20
189 NaN NaN
190 NaN NaN
191 NaN NaN
192 NaN NaN
193 NaN NaN
.. ... ...
247 106.5125 106.46325
248 106.8455 106.55425
249 107.6285 106.90725
250 108.4815 107.34275
251 109.4515 107.76575
[63 rows x 2 columns]
Moving Averages for MSFT
MA10 MA20
63 NaN NaN
64 NaN NaN
65 NaN NaN
66 NaN NaN
67 NaN NaN
.. ... ...
121 302.295999 294.225998
122 305.453998 295.434499
123 307.147998 296.875499
124 307.675998 297.888998
125 307.846997 299.030498
[63 rows x 2 columns]
Moving Averages for NFLX
MA10 MA20
126 NaN NaN
127 NaN NaN
128 NaN NaN
129 NaN NaN
130 NaN NaN
.. ... ...
184 323.519995 328.057498
185 324.478998 327.753999
186 325.906000 327.973500
187 327.797000 327.902000
188 328.793002 327.965001
[63 rows x 2 columns]
## visualizing the moving averages
for ticker, group in df.groupby('Ticker'):
fig = px.line(group, x='Date', y=['Close', 'MA10', 'MA20'],
title=f"{ticker} Moving Averages")
fig.show()
The output shows four separate graphs for each company. When the MA10 crosses above the MA20, it is considered a bullish signal indicating that the stock price will continue to rise. Conversely, when the MA10 crosses below the MA20, it is a bearish signal that the stock price will continue falling.
Volatility is a measure of how much and how often the stock price or market fluctuates over a given period of time. Let's analyze the volatility of all companies
df['Volatility'] = df.groupby('Ticker')['Close'].pct_change().rolling(window=10).std().reset_index(0,drop=True)
fig = px.line(df, x='Date', y='Volatility',
color='Ticker',
title='Volatility of All Companies')
fig.show()
High volatility indicates that the market experiences large and frequent price fluctuations and vice versa.
Let's analyze the correlation between the stock prices of Apple and Microsoft
# create a DataFrame with the stock prices of Apple and Microsoft
apple = df.loc[df['Ticker'] == 'AAPL', ['Date', 'Close']].rename(columns={'Close': 'AAPL'})
microsoft = df.loc[df['Ticker'] == 'MSFT', ['Date', 'Close']].rename(columns={'Close': 'MSFT'})
df_corr = pd.merge(apple, microsoft, on='Date')
# create a scatter plot to visualize the correlation
fig = px.scatter(df_corr, x='AAPL', y='MSFT',
trendline='ols',
title='Correlation between Apple and Microsoft')
fig.show()
There is a strong linear relationship between the stock prices of Apple and Microsoft, which means that when the stock price of Apple increases, the stock price of Microsoft also tends to increase. It is a sign of a strong correlation or similarity between the two companies, which can be due to factors such as industry trends, market conditions, or common business partners or customers.
A suggestion for investors or potential investors would be to diversify their portfolio by investing in both companies, as both stocks may offer similar potential returns and risks.